<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/23 0023
 * Time: 11:07
 */

namespace app\api\controller;

use app\admin\model\Tenant;
use app\admin\model\Store;
use app\admin\model\Wxcomponentconf;
use app\admin\model\Wxcomponentconftmp;
use app\admin\model\Wxframeconf;
use app\admin\model\Wxframeconftmp;
use app\admin\model\Storeproduct;
use app\admin\model\Article;
use app\admin\model\Coupon;
use app\admin\model\Groupproduct;
use app\admin\model\Integralproducts;
use app\admin\model\Popon;
use app\admin\model\Product;
use think\Request;

/**
 * Class HomeFrame
 * @package app\api\controller
 * 获取首页模板，首页为自定义页面
 * 丁应清
 */
class HomeFrame extends BaseController
{
    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 请取商户首页模板
     * 传入参数tenantId
     */
    public function getHomeFrame()
    {
        $param = self::getHttpParam();
        if (empty($param->tenantId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'tenantId不能为空');
        } else if (empty($param->storeId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'storeId不能为空');
        } else {
            $tenantId = $param->tenantId;
            $storeId = $param->storeId;
            $wxframeconf = Wxframeconf::where(['tenantId' => $tenantId, 'storeId' => $storeId])->order('orderNo,createDate DESC')->select();
            if (empty($wxframeconf)) {
                return $this->defaultModel($tenantId);
            } else {
                foreach ($wxframeconf as $k => $v) {                    
                    if($v['type'] == 10) {  //推荐内容
                        $component = [];
                        switch ($v['contentType']) {  //根据contentType取对应数据
                            case '1':  //商品
                                switch ($v['orderType']) {
                                    case 1: $order = 'a.created DESC';break;
                                    case 2: $order = 'a.orderNo ASC';break; // TODO
                                    case 3: $order = 'a.orderNo DSC';break; // TODO
                                    case 4: $order = 'a.recommendation ASC';break;
                                    default : break;
                                }
                                $list = Storeproduct::field('b.id linkId,b.title displayName,b.imgUrl,a.orderNo,b.currentPrice,b.memberPrice')->alias('a')->join('product b','a.product_id=b.id')->order($order)->where(['store_id'=>$storeId,'recommendation'=>1])->select();
                                $list = $this->getLinkType($list,1);
                                break;
                            case '2':  //文章
                                switch ($v['orderType']) {
                                    case 1: $order = 'createDate DESC';break;
                                    case 2: $order = 'readCount DSC';break;
                                    case 3: $order = 'createDate ASC';break; // TODO
                                    case 4: $order = 'recommendation ASC';break;
                                    default : break;
                                }
                                $list = Article::field('id linkId,title displayName,iconUrl imgUrl,orderNo,readCount,createDate')->where(['tenantId'=>$tenantId,'recommendation'=>1])->order('orderNo')->select();
                                $list = $this->getLinkType($list,7);
                                break; 
                            case '3':   //拼团商品
                                switch ($v['orderType']) {
                                    case 1: $order = 'a.create_time DESC';break;
                                    case 2: $order = 'a.sort DSC';break; // TODO
                                    case 3: $order = 'a.sort ASC';break; // TODO
                                    case 4: $order = 'a.recommendation ASC';break;
                                    default : break;
                                }
                                $list = Groupproduct::field('a.id linkId,b.title displayName,b.imgUrl,a.sort orderNo,b.groupPrice,a.groupSuccCount,b.currentPrice')->alias('a')->join('product b','a.productId=b.id')->where(['storeId'=>$storeId,'recommendation'=>1,'status'=>['neq',2]])->order($order)->select();
                                $list = $this->getLinkType($list,6);
                                break;
                            case '4':  //积分兑换
                                switch ($v['orderType']) {
                                    case 1: $order = 'a.create_time DESC';break;
                                    case 2: $order = 'a.sort DESC';break; // TODO
                                    case 3: $order = 'a.sort ASC';break; // TODO
                                    case 4: $order = 'a.recommendation ASC';break;
                                    default : break;
                                }
                                $list = Integralproducts::field('a.productId linkId,b.title displayName,b.imgUrl,a.sort orderNo,b.integralPrice,b.currentPrice')->alias('a')->join('product b','a.productId=b.id')->where(['storeId'=>$storeId,'recommendation'=>1])->order($order)->select();
                                $list = $this->getLinkType($list,11);
                                break;
                            default:
                                $list = [];
                        }
                        $wxframeconf[$k]['sub'] = $list;
                    } else if($v['type'] == 9){  //代金券
                        $curTime = time();
                        $url = 'http://'.$_SERVER['HTTP_HOST'].'/public/static/assets/pages/image/';
                        $wxframeconf[$k]['img'] = $url . 'quan'.$v['displayType'].'-2.png';
                        $list = Coupon::field('id linkId,name displayName,value2,type,value1,leftCount,isGetPhone')->where(['tenantId'=>$tenantId,'storeId'=>$storeId])->where('endTime > '.$curTime.' and getCond = 1')->where('leftCount > 0 or isLimit = 1')->select();
                        $list = $this->getCoupon($list);
                        $wxframeconf[$k]['sub'] = $list;
                    } else {
                        $wxcomponentconf = Wxcomponentconf::where('frameId', $v['id'])->order('orderNo')->select();

                        // 附近门店
                        if($v['type'] == 11){
                            $lat = input('post.lat');
                            $lng = input('post.lng');

                            $actionWhere = [
                                'tenantId' => $tenantId,
                                'lat' => $lat,
                                'lng' => $lng,
                                'wheredata' => ''
                            ];
                            // 由近到远得到店铺列表
                            $storeList = action('api/TenantStore/getStoreSortForDistance', $actionWhere);
                            $wxcomponentconf = $storeList;
                        }
                        $wxframeconf[$k]['sub'] = $wxcomponentconf;
                    }
                }
                return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $wxframeconf);
            }
        }
    }

    /**
     * @param $tenantId
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 查看默认模板
     */
    private function defaultModel($tenantId)
    {
        $tenant = Tenant::where('id', $tenantId)->find();
        if (empty($tenant)) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '该商户不存');
        } else {
            $wxframeconftmp = Wxframeconftmp::where('category', $tenant->category)->order('orderNo')->select();
            for ($i = 0; $i < count($wxframeconftmp); $i++) {
                $wxcomponentconftmp = Wxcomponentconftmp::where('frameId', $wxframeconftmp[$i]->id)->order('orderNo')->select();
                foreach ($wxcomponentconftmp as $k => $v) {
                    if($v['linkType'] == '1') {  //链接类型为商品，另取商品价格
                        $pRow = Product::where('id',$v['linkId'])->field('currentPrice,memberPrice')->find();
                        $wxcomponentconftmp[$k]['currentPrice'] = $pRow['currentPrice'];
                        $wxcomponentconftmp[$k]['memberPrice'] = $pRow['memberPrice'];
                    }
                }
                $wxframeconftmp[$i]['sub'] = $wxcomponentconftmp;
            }
            return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $wxframeconftmp);
        }
    }

    /**
     * 获取小程序首页广告
     * @Author   jiating
     * @DateTime 2018-05-14
     * @param    string     $tenantId 商户ID
     */
    public function getHomeAdvertisment() {
        $param = self::getHttpParam();
        if (empty($param->tenantId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'tenantId不能这空');
        }
        $tenantId = $param->tenantId;
        $popon = Popon::where(['tenantId'=>$tenantId,'status'=>1])->find();
        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $popon);
    }

    /**
     * 设置推荐内容模块中的组件
     * @param    array   $list 取出的数据
     * @param    int     $type linkType
     */
    private function getLinkType($list,$type) {
        foreach ($list as $k => $v) {
            $list[$k]['linkType'] = $type;
        }
        return $list;
    }

    /**
     * 组装优惠券列表信息
     * @param    array     $list 优惠券列表
     */
    private function getCoupon($list) {
        foreach ($list as $k => $v) {
            if($v['type'] == '无限制') {
                $list[$k]['condition'] = '无门槛';
            } else {
                $list[$k]['condition'] = '满'.($v['value1']/100).'可用';
            }
             $list[$k]['value1'] = $v['value1']/100;
             $list[$k]['value2'] = $v['value2']/100;
        }
        return $list;
    }

}